package cn.zbmao.web.interceptor;

import cn.zbmao.web.bean.User;
import cn.zbmao.web.util.dao.DaoFactory;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;

import javax.servlet.http.Cookie;

public class MyIntercepter implements Interceptor {
    /**
     * 访问登陆拦截
     * @param ai
     */
	public void intercept(ActionInvocation ai) {
		User user = ai.getController().getSessionAttr("user");
        Cookie cookie=ai.getController().getCookieObject("zbmao_id");

        String cook=ai.getController().getCookie("zbmao_id");
		String url = ai.getActionKey();
//        进入登陆页面时判断是否有cookie,有的话删除该cookie
		if( url.startsWith("/account/ajax")||"/login".equals(url) || "/login/loginto".equals(url)||url.startsWith("/signup")||url.startsWith("/resetpwd")||url.startsWith("/oauth")){
            if(cookie!=null){
                if("/login".equals(url) || "/login/loginto".equals(url)) {
                    Cookie newCookie=new Cookie("zbmao_id",null);
                    newCookie.setMaxAge(0);
                    newCookie.setPath("/");
                    ai.getController().getResponse().addCookie(newCookie);
                }

            }

            ai.invoke();

		}else{
//            先判断session中是否有用户信息，在进行cookie判断，如果都不存在则返回登陆页面
			if(user!=null){
				ai.invoke();
				ai.getController().setAttr("user_name", user.get("user_name"));
			}else{

                if(cook!=null && cook.length()==24){
                    User u = DaoFactory.getUserDao().getUserByZbmId(cook);
                    if (u != null) {
                        ai.getController().setSessionAttr("user", u);
//                        Date date = DateUtil.getNowToDate();
//                        if (date != null) {
//                            DaoFactory.getUserDao().updateUserLoginTime(date, u);
//                        }

                        ai.invoke();
                        ai.getController().setAttr("user_name", u.get("user_name"));

                    } else {
                        ai.getController().redirect("/login");
                    }

                }else {
                    ai.getController().redirect("/login");
                }
			}

		}
	}

}
